package code.concurrent;

// 多线程打印奇偶数，怎么控制打印的顺序
public class PrintOddEven {
    private static final Object lock = new Object();
    private static int count = 1;
    private static final int MaxCount = 10;

    public static void main(String[] args) {
        Runnable printOdd = () -> {
            synchronized (lock) {
                while (count <= MaxCount) {
                    if (count % 2 != 0) {
                        System.out.println(Thread.currentThread().getName() + ":"+count++);
                        lock.notify();
                    }else {
                        try {
                            lock.wait();
                        }catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };

        Runnable printEven = () -> {
            synchronized (lock) {
                while (count <= MaxCount) {
                    if (count % 2 == 0) {
                        System.out.println(Thread.currentThread().getName() + ":"+count++);
                        lock.notify();
                    }else {
                        try {
                            lock.wait();
                        }catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };

        Thread odd = new Thread(printOdd, "printOdd");
        Thread even = new Thread(printEven, "printEven");
        odd.start();
        even.start();
    }
}
